package com.yys.gulimall.search.service.impl;/*
 * @author zq
 */

import com.alibaba.fastjson.JSON;
import com.yys.common.to.es.SkuEsTo;
import com.yys.gulimall.search.config.ElasticConfig;
import com.yys.gulimall.search.constant.EsConstant;
import com.yys.gulimall.search.service.ProductSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ProductSaveServiceImpl implements ProductSaveService {
    @Autowired
    RestHighLevelClient restHighLevelClient;


    @Override
    public boolean productStatusUp(List<SkuEsTo> skuEsTos) throws IOException {
        // 保存到es
        // 给es创建索引
        // 建立映射关系
        // ----- 以上使用 postman 或 kibana 添加

        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsTo skuEsTo : skuEsTos) {
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            indexRequest.id(skuEsTo.getSkuId().toString());
            String skuEsToJsonString = JSON.toJSONString(skuEsTo);
            indexRequest.source(skuEsToJsonString, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        // 批量保存
        BulkResponse bulk = null;

        try {
            bulk = restHighLevelClient.bulk(bulkRequest, ElasticConfig.COMMON_OPTIONS);
        } catch (Exception e) {
            log.error("es链接异常:{}",e);
            return false;
        }

        boolean hasFailures = bulk.hasFailures();
        //TODO 处理批量错误
        if (hasFailures) {
            List<String> failIds = Arrays.stream(bulk.getItems()).map(BulkItemResponse::getId).collect(Collectors.toList());
            log.error("商品上架错误",failIds);
        } else {
            log.info("商品上传es成功");
        }
        return !hasFailures;
    }
}
